package com.funny.stock.base.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import ch.qos.logback.core.util.CloseUtil;

/**
 * @author pengl
 * @date 2020/11/21
 **/
public class CommonUtils {

    public static <T> T getFirstItem(Collection<T> collection){
        if(collection == null || collection.size() == 0) return null;

        if(collection instanceof List){
            return ((List<T>) collection).get(0);
        }

        return collection.iterator().next();
    }

    public static <T> T getLastItem(Collection<T> collection){
        if(collection == null || collection.size() == 0) return null;

        if(collection instanceof List){
            return ((List<T>) collection).get(collection.size() - 1);
        }

        T item = null;
        Iterator<T> iterator = collection.iterator();
        while (iterator.hasNext()){
            item = iterator.next();
        }
        return item;
    }

    public static String getStackTraceInfo(Throwable e) {
        StringWriter sw = null;
        PrintWriter pw = null;

        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);

            e.printStackTrace(pw);

            pw.flush();
            sw.flush();
            return sw.toString();
        } catch (Exception ex) {
            return "error:" + ex.getMessage();
        } finally {
            CloseUtil.closeQuietly(sw);

            CloseUtil.closeQuietly(pw);
        }

    }
}
